package com.framework.seedkit.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

public class AppActivityManager {
	
	private static Stack<Activity> activityStack;
	private static AppActivityManager instance;
	
	private AppActivityManager() {}

	public static AppActivityManager getAppManager() {
		if(instance == null) {
			instance = new AppActivityManager();
		}
		return instance;
	}

	public void addActivity(Activity activity) {
		if(activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	public Activity currentActivity() {
		Activity activity = activityStack.lastElement();
		return activity;
	}

	public void finishActivity() {
		Activity activity = activityStack.lastElement();
		finishActivity(activity);
	}

	public void finishActivity(Activity activity) {
		if(activity != null) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	public void finishActivity(Class<?> cls) {
		for (Activity activity : activityStack) {
			if(activity.getClass().equals(cls)) {
				finishActivity(activity);
			}
		}
	}

	public void finishAllActivity(){
		for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
            	activityStack.get(i).finish();
            }
	    }
		activityStack.clear();
	}

	public void AppExit(Context context) {
		try {
			finishAllActivity();
			ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			activityMgr.restartPackage(context.getPackageName());
			
//			StatisticsUtils.cleanStatCache(context);
			System.exit(0);
		} catch (Exception e) {	}
	}
	
	public Stack<Activity> getActivitySatck() {
		return activityStack;
	}
}